<?php
// 【最终完整版】m-merchant/login_handler.php
session_start();
header('Content-Type: application/json; charset=utf-8');

include_once("../untils/conn.php"); 
mysqli_query($con, "set names utf8");

$response = ['status' => -1, 'msg' => '未知错误'];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $account = $_POST['account'] ?? '';
    $password = $_POST['password'] ?? '';

    if (empty($account) || empty($password)) {
        $response['msg'] = '账号或密码不能为空';
    } else {
        $account_safe = mysqli_real_escape_string($con, $account);
        $password_safe = mysqli_real_escape_string($con, $password);

        $sql = "SELECT * FROM proxy WHERE proxy_acc = '$account_safe'";
        $result = mysqli_query($con, $sql);
        $row = mysqli_fetch_assoc($result);

        if (!$row) {
            $response['msg'] = '账号不存在';
        } elseif ($row['proxy_sta'] == 0) {
            $response['msg'] = "您的账号已被封禁！";
        } elseif ($row['proxy_pass'] != $password_safe) {
            $response['msg'] = '账号或密码错误';
        } else {
            // Token 生成逻辑
            $secret_key = 'kkcc.vip-is-the-best-!@#$%';
            $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
            $payload = json_encode([
                'iat' => time(),
                'exp' => time() + (60 * 60 * 24 * 7),
                'data' => [ 'proxy_id' => $row['proxy_id'], 'proxy_acc' => $row['proxy_acc'] ]
            ]);
            $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
            $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
            $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secret_key, true);
            $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
            $token = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

            $response['status'] = 0;
            $response['msg'] = '登录成功！';
            $response['token'] = $token;
        }
    }
} else {
    $response['msg'] = '无效的请求方式';
}
echo json_encode($response);
mysqli_close($con);
?>